<?php 
class GetListHelper extends AppHelper {

    var $controller = null;
    var $helpers = array('Html','Form','Time','Number','Paginator','Session');
    private $userFunction;
    private $_html =array('color'=>null,'width'=>null,'height'=>null,'style'=>null,'align'=>null,'border'=>null,'class'=>null);
    private $_dato;
    private $_key;
    public $i; // para jalar el numero del registro desde el callback


    function startup(&$controller){
        $this->controller = $controller;
    }


    var $tags = array(
        'table' => '<table>%s</table>',
		'tr' => '<tr>%s</tr>',
		'td' => '<td %s>%s</td>',
		'th' => '<th %s>%s</th>',
		'strong' => '<strong>%s</strong>',
                'a'=>'<a href="%s">%s</a>',
                'aclass'=>'<a href="%s" class="%s">%s</a>');
    
    function getProperty($pro=array()){
                $property=' ';
                foreach($pro as $name => $value){
                    if(!is_array($name)){
                        $property .= $name.'="'.$value.'" ';
                    }
                }
                return $property;
    }
    function getId($key,$id=false){
                $valor='';
                if($id==true){
                    $strin	= str_replace(array('[', ']'), array('',''), str_replace(array('][','_'),array('.','.'),$key));
                    $explod = explode('.',$strin);
                    foreach($explod as $v=>$a){
                        $valor .= ucwords($a);
                    }
                }else{
                    $valor = str_replace(array('[', ']'), array('',''), str_replace('][','.',$key));
                }
                return $valor;
    }
	
    function transform($cadena, $datatype = null){
                if (empty($datatype)){
                    if(is_numeric($cadena)){
                        if(count(explode('.',$cadena))== 2){
                            $cadena = $this->Number->precision($cadena, 2);
                        }
                    } else if (is_bool($cadena)){
                        $cadena = $cadena==true || $cadena==1?'NO':'SI';
                    } else if($this->is_date($cadena)){
                        $cadena = $this->Time->format('d/m/Y',$cadena);
                    } 
                } else {
                    switch(low($datatype)){
                        case 'integer':
                            $cadena = round($cadena);
                            break;
                        case 'numeric':
                            $cadena = $this->Number->precision($cadena, 2);
                            break;
                        case 'numeric4':
                            $cadena = $this->Number->precision($cadena, 4);
                            break;
                        case 'boolean':
                            $cadena = $cadena==true || $cadena==1?'SI':'NO';
                            break;
                        case 'date':
                            $cadena = $this->Time->format('d/m/Y',$cadena);
                            break;
                        case 'time':
                            $cadena = $this->Time->format('h:i:s a',$cadena);
                            break;
                        case 'datetime':
                            $cadena = $this->Time->format('d/m/Y h:i:s a',$cadena);
                            break;
                        case 'relativedatetime':
                            $date = $this->Time->format('d/m/Y',$cadena);
                            $date = explode('/',$date);
                            $time = $this->Time->format('H:i:s',$cadena);
                            $time = explode(':',$time);
                            $nowDate = Date('d/m/Y');
                            $nowDate = explode('/',$nowDate);
                            $nowTime = Date('h:i:s');
                            $nowTime = explode(':',$nowTime);

                            if ($date[0].$date[1].$date[2] == $nowDate[0].$nowDate[1].$nowDate[2]){ // mismo dia                                
                                if ($nowTime[0] == $time[0] && $nowTime[1] == $time[1])
                                    $cadena = ($nowTime[2] - $time[2]).' seg. atras';
                                else if ($nowTime[0] == $time[0])
                                    $cadena = ($nowTime[1] - $time[1]).' min. atras';
                                else
                                    $cadena = ($nowTime[0] - $time[0]).' hor. atras';
//                                $cadena = $this->restaFechas($cadena, date(''));
                            } else {
                                if ($nowDate[2] == $date[2] && $nowDate[1] == $date[1])
                                    $cadena = ($nowDate[0] - $date[0]).' d&iacute;a atras';
                                else
                                    $cadena = $this->Time->format('d/m/Y',$cadena);;
                            }

                            break;
                        case 'string':
                            break;
                        default:
                            break;
                     }
                }
		return $cadena;
    }
	
    function getValue($dato, $key, $strong = false, $transform = true, $datatype = null){
                $key = $key.'';
		$val = str_replace('[','',$key);
                $val = $val.'';
		$dat = explode(']',$val);
		$valor = $dato;
		foreach($dat as $d){
                    if($d != false){
                        $valor = isset($valor[$d])?$valor[$d]:false;
                    }
		}
                if ($transform && !empty($valor) && trim($valor)!='')
                    $valor = $this->transform($valor, $datatype);

                if ($strong)
                    return sprintf($this->tags['strong'], $valor);
                else
                    return trim($valor);
    }
	
    function getButton($f){
		$form 	= $this->Form;
		$boton ='';
                $boton.=sprintf($this->tags['aclass'], Router::url(array('controller'=>'Home','action'=>'index')), 'lnkbutton btnback', 'Volver');
                $boton.=sprintf($this->tags['aclass'], Router::url('add'), 'lnkbutton btnnew', 'Nuevo');
		$boton.= $form->submit('Eliminar', array(
			'div' => false,
			'value'=>true,
			'name'=>'delete',
			'class'=>'btnerase'
		));

		return $boton;
    }
	
    private function formatHtml($arg = array()){
            //$_temp = array_intersect_assoc($this->_html, $arg);
            $array = array();
            foreach($this->_html as $key=>$value){
                    if(isset($arg[$key]))
                            $array[$key] = $arg[$key];
            }
            return $this->getProperty($array);
    }

    function evalLink($link = array()){
            $_temp = $link;
            if(gettype($link)=== 'string'){
                if (strpos($link,'?') > 0)
                    $link = array('action'=>$_temp);
                else
                    $link = array('action'=>$_temp, $this->getValue($this->_dato,$this->_key, false, false));
            } else if (gettype($link)=== 'array') {
                if(isset($link['?'])){
                    foreach($link['?'] as &$value){
                        $value = $this->getValue($this->_dato,$value, false, false);
                    }
                }
                if(isset($link[0])){
                    $link[0] = $this->getValue($this->_dato,$link[0], false, false);
                } else {
                    $link[0] = $this->getValue($this->_dato,$this->_key, false, false);
                }
            }
            return $link;
    }
    
    // reportes
     function evalReport($link = array()){
            $_temp = $link;
            if(gettype($link)=== 'string'){
                    $link = array('action'=>$_temp, $this->getValue($this->_dato,$this->_reporte, false, false));
                    return $link;
            }

            if(isset($link['?'])){
                    foreach($link['?'] as &$value){
                            $value = $this->getValue($this->_reporte,$value, false, false);
                    }
            }
            if(isset($link[0])){
                    $link[0] = $this->getValue($this->_dato,$link[0], false, false);
            } else {
                    $link[0] = $this->getValue($this->_dato,$this->_reporte, false, false);
            }
            return $link;
    }
    
    function getValues($key, $value){
            $datatype = !empty($value['datatype'])?$value['datatype']:null;
            $strong = array_key_exists('strong', $value)?true:false;
            if(!empty($value['fields'])){
                    $func = new ReflectionFunction('sprintf');
                    $data = array();
                    array_push($data,$value['fields'][1]);
                    foreach($value['fields'][0] as $field=>$values){
                        array_push($data,$this->getValue($this->_dato,$values,$strong, true, $datatype));
                    }
                    return $func->invokeArgs($data);
            } else {
                    $field = $this->getValue($this->_dato,$key,$strong, true, $datatype);
                    return $field;
            }
    }

    function href($key, $value){
            if (array_key_exists('href_'.$this->getId($key,true), $this->_dato)){
                $value['href'] = $this->_dato['href_'.$this->getId($key,true)];
                $link = $value['href'];
            } else {
                if(gettype($value['href']) === 'string'){
                    $link = ''.$value['href'].'/'.$this->getValue($this->_dato,$this->_key, false, false).'';
                } else if(gettype($value['href']) === 'array'){
                    $link = $value['href'] += array($this->getValue($this->_dato,$this->_key, false, false));
                } else {
                    $link = $this->getValue($this->_dato,$this->_key, false, false);
                }
            }
            $link = sprintf($this->tags['a'], $this->Html->url($link),  $this->getValues($key, $value));
            return $link;
    }
    
    function getList($arg=array()){
            $n = chr(13); // igual que <br>;
            $form = $this->Form;
            $html = $this->Html;
            $session = $this->Session;
            $paginator = $this->Paginator;
            foreach($arg[1]['config'] as $key=>$llave){
                if(array_key_exists('key', $llave) && $llave['key']==true){
                     $id = $key ;
                     $this->_key = $id;
                     break;
                }
            }            

        if(empty(AppController::$text_buscar)){ 
			$q=''; 
		} else { 
			$q = '&q='.AppController::$text_buscar; 
		}
		$paginator->options(array('url'=>array('?'=>'limite='.AppController::$limit_index.''.$q)));
        // solo variable de reporte
        foreach($arg[1]['config'] as $keys=>$llaves){
                if(array_key_exists('report', $llaves) && $llaves['report']==true){
                     $report = $keys ;
                     $this->_reporte = $report;
                     break;
                }
            }
            if(!isset($arg[1]['adition']['paginator']))
                $arg[1]['adition']['paginator'] = true;
            $body ='';
            $body.= '<div style="display:none">'.$session->flash().'</div>';
            // verificamos si tiene busqueda
            //$limite = 20;
            if(!isset($arg[1]['adition']['find']))
                    $arg[1]['adition']['find'] = true;
            if($arg[1]['adition']['find']===true){
                $accionbusqueda = isset($arg[1]['adition']['action']) ? $arg[1]['adition']['action'] : 'index';
                $id = isset($arg[1]['adition']['id']) ? array($arg[1]['adition']['id']) : array();

                $body.='<div id="busqueda">';
                $body.= $form->create(null, array('url' => array('action' => $accionbusqueda)+$id,'type'=>'get'));
                $body.= $form->input('q',array(
                    'label'=>false,
                    'div'=>false,
                    'title' => 'utilice ; para realizar búsquedas combinadas',
                    'id'=>'filterBox',
                    'maxlength'=>30,
                    'size'=>30,
                    'after'=>
                        '&nbsp;'.$form->submit('Buscar',array('div'=>false,'class'=>'btnfind')).
                        '&nbsp;'.$form->input('pagesize',array( 'value'=>'20','type'=>'hidden'))
                ));
                $body.= $form->end();
                $body.='</div>';
                $body.='<p/>';
            }
            // verificamos si tiene form
            if(!empty($arg[1]['form'])){
				$html_form = '';
				if(!empty($arg[1]['form']['html'])){
					$html_form = $arg[1]['form']['html'];
					unset($arg[1]['form']['html']);
				}                 
				$body .= $form->create(null,$arg[1]['form']).$n;
				$body .= $html_form;
            }

            if ($arg[1]['adition']['paginator']){
                $body.='<div align="left">'.$n;
                $body.=$paginator->counter(array('format' => __('Pagina %page% de %pages%, registros del %start% al %end%  de %count% en total.', true)));
                $body.='</div><p/>'.$n;
            }

            $body.='<div id="resultados" class="index">';
            // verificamos envio de table !='', o se poner por defecto
            if(empty($arg[1]['table'])){
                $table = array('class'=>'celda','border'=>'0');
            } else {
                $table = $arg[1]['table'];
            }            
            
            // verificamos envio de title_groups !='', o se poner por defecto
            if(empty($arg[1]['title_groups'])){
                $groups = array();
            } else {
                $groups = $arg[1]['title_groups'];
            }
            $groupkeys = array_keys($groups);

            $body.='<table'.$this->getProperty($table).'>'.$n;
            $body.='<thead>'.$n;
            $body.='<tr>'.$n;
            $first = false;
            $done = false;


            if (!empty($groups)){
                $last = -1;
                foreach($arg[1]['config'] as $_fields => $head){
                    if($head['type'] == 'hidden') continue;
                    if (array_key_exists('group', $head))
                        $group = $head['group'];
                    else
                        $group = -1;
                    if (!array_key_exists('order', $head)) 
                        $order = true;
                    else
                        $order = $head['order'];

                    if ($group == -1){
                        $params = ' rowspan="2" ';
                        if($order && $arg[1]['adition']['paginator']){
                            if (isset($head['sort'])){
                                $title = $paginator->sort(ucwords($head['title']), $this->getId($head['sort']),array('class'=>'accion'));
                            } else {
                                $title = $paginator->sort(ucwords($head['title']), $this->getId($_fields),array('class'=>'accion'));
                            }
                        } else {
                            $title = ucwords($head['title']);
                        }
                        $body.= sprintf($this->tags['th'], $params.$this->formatHtml($head), $title);
                    } else {
                        if ($group == $last) continue;
                        $title = $groupkeys[$group];
                        $colspan = $groups[$groupkeys[$group]];
                        $body.= sprintf($this->tags['th'], " colspan='{$colspan}' ", $title);
                        $last = $group;
                    }
                }
                $first = false;
                $body.='</tr>'.$n;
                $body.='<tr>'.$n;
            }

            foreach($arg[1]['config'] as $_fields => $head){
                if($head['type'] == 'hidden') continue;
                
                if (array_key_exists('group', $head))
                    $group = $head['group'];
                else
                    $group = -1;
                if (!empty($groups) && $group == -1) continue;
                
                if (!array_key_exists('order', $head)) {
                    $order = true;
                } else {
                    $order = $head['order'];
                }

                if($order && $arg[1]['adition']['paginator']){
                    if (isset($head['sort'])){
                        $title = $paginator->sort(ucwords($head['title']), $this->getId($head['sort']),array('class'=>'accion'));
                    } else {
                        $title = $paginator->sort(ucwords($head['title']), $this->getId($_fields),array('class'=>'accion'));
                    }
                } else {
                    $title = ucwords($head['title']);
                }
                $body.= sprintf($this->tags['th'], $this->formatHtml($head), $title);
                
            }
            $body.='</tr>'.$n;
            $body.='</thead>'.$n;
            $body.='<tbody>'.$n;
            $this->i = 0;
            $body_h = '';
            foreach($arg[1]['data'] as $dato){          
                $class = '';
                $_class = '';
                $color = '';
                $body_h ='';
                if ($this->i++ % 2 == 0) {
                    $class = ' altrow ';
                }
                $this->_dato = $dato;
                if(!empty($this->userFunction)){
                    $func = new ReflectionFunction($this->userFunction);
                    $this->_dato['Html'] = $this->Html;
                    $this->_dato['Number'] = $this->Number;
                    $this->_dato['Session'] = $_SESSION;
                    $_class = $func->invokeArgs(array(&$this->_dato,$this));
                }
                $body .='<tr height="30px" class="'.$class.$_class .'"'.$color.'>'.$n;
                foreach($arg[1]['config'] as $key=>$value){
                    if(!empty($value['strong'])){
                        $strong=true;
                    } else {
                        $strong=false;
                    }
                    if (!empty($value['id']))
                        $idName = " id=\"{$value['id']}\" ";
                    else
                        $idName = '';										
                    switch($value['type']){
                        case 'fields':
                            if(!empty($value['href'])){
                                $body.= sprintf($this->tags['td'], $idName.$this->formatHtml($value), $this->href($key, $value).$body_h);
                            } else {                                
                                $body.= sprintf($this->tags['td'], $idName.$this->formatHtml($value), $this->getValues($key, $value).$body_h);
                            }
                            $body_h ='';
                            break;
                        case 'checkbox':
                            $check = $form->input(str_replace(array('[',']'),array('',''),$key), array(
                                    'type'=>'checkbox',
                                    'div'=>false,
                                    'label'=>false,
                                    'id'=>$this->getID($key,true),
                                    'name'=> 'data['.$this->i.']'.$key,
                                    'value'=>$this->getValue($this->_dato, $id, false, true, 'string')
                            ));
                            $body.= sprintf($this->tags['td'], $idName.$this->formatHtml($value), $check.$body_h);
                            $body_h ='';
                            break;
                        case 'button':
                            if(!isset($value['var'])){
                                    $value['var'] = $id;
                            }
                            if (array_key_exists('href_'.$this->getID($key,true), $this->_dato))
                                    $value['href'] = $this->_dato['href_'.$this->getID($key,true)];
                            
                            $button = $html->link( __(str_replace(array('[', ']'),array('', ''), $key), true),
                                    $this->evalLink($value['href']), $value);
                            $body.= sprintf($this->tags['td'], $idName.$this->formatHtml($value), $button.$body_h);
                            $body_h ='';
                            break;
                        case 'print':
                            if(!isset($value['var'])){
                                    $value['var'] = $id;
                            }
                            $button = $html->link( __(str_replace(array('[', ']'),array('', ''),$key), true),
                                    $this->evalReport($value['href']),$value);
                            $body.= sprintf($this->tags['td'], $idName.$this->formatHtml($value), $button.$body_h);
                            $body_h ='';
                            break;
                        case 'print':
                            if(!isset($value['var'])){
                                    $value['var'] = $id;
                            }
                            $button = $html->link( __(str_replace(array('[', ']'),array('', ''),$key), true),
                                    $this->evalReport($value['href']),$value);
                            $body.= sprintf($this->tags['td'], $idName.$this->formatHtml($value), $button.$body_h);
                            $body_h ='';
                            break;
                        case 'hidden':
                            $body_h .= $form->input($key,array(
                                'type'=>'hidden',
                                'id'=>$this->getID($key,true),
                                'name'=> 'data['.$this->i.']'.$key,
                                'default'=>$this->getValue($this->_dato, $key, false, true, 'string')
                            ));
                            break;
                        case 'counter':
                            $body.= sprintf($this->tags['td'], $idName.$this->formatHtml($value), $this->i.$body_h);
                            $body_h ='';
                            break;
                        case 'input':
                            $input = $form->input($key, array_merge(array(                                
                                'id'=>$this->getID($key,true),
                                'name'=> 'data['.$this->i.']'.$key,
                                'default'=>$this->getValue($this->_dato, $key, false, true, 'string')
                            ),$value['options']));
                            $body.= sprintf($this->tags['td'], $idName.$this->formatHtml($value), $input.$body_h);
                            $body_h ='';
                            break;
                        case 'text':
                            $body_h .= $form->input($key,array('label'=>false, 'div'=>false,'id'=>$this->getID($key,true),'size'=>7,'name'=> 'data['.$this->i.']'.$key));
                            $body.= sprintf($this->tags['td'], $idName.$this->formatHtml($value),$body_h);
                            $body_h ='';
                            break;
                    }
                }
                $body.='</tr>'.$n;
            }			
			// En caso no de tener resultados mostramos el mensaje
			if(empty($arg[1]['data'])){ 
			$body .='<tr>'.$n;
			$body .='<td colspan="'.count($arg[1]['config']).'" align="center">'.$n;			
			$body .='No hay registros disponibles en este momento'.$n;						
			$body .='</td>'.$n;			
			$body .='</tr>'.$n;
			}
            // PAGINAR			
            if($arg[1]['adition']['paginator'] == true){
                $body.='<tr>'.$n;
                $body.='<td colspan="'.count($arg[1]['config']).'" align="left" valign="bottom">'.$n;
                $body .=  $paginator->first($html->image(
                        'first.png',array(
                            'alt' => __('Primero', true),
                            'border' => 0,
                            'class' =>'first')),
                        array('escape'=>false)).
                        $paginator->prev
                        ($html->image('prev.png',array(
                            'alt' => __('Anterior', true),
                            'border' => 0,
                            'class' =>'prev')),
                                array('escape'=>false)).' '.
                        $paginator->numbers().' '.
                        $paginator->next($html->image(
                                'next.png',array(
                                    'alt' => __('Siguiente', true),
                                    'border' => 0,
                                    'class' =>'next')),
                                array('escape'=>false)).
                        $paginator->last($html->image(
                                'last.png',array(
                                    'alt' => __('Último', true),
                                    'border' => 0,
                                    'class' =>'last')),
                                array('escape'=>false));
                $body.='</td>'.$n;
                $body.='</tr>'.$n;
            }
			
            $body.='</tbody>'.$n;
            $body.='</table>'.$n;
            $body.=$body_h;

            $body.='</div>'.$n;//terminamos el div = resultados

            $body .= '<div class="actions"><p>'.$n;
            if(empty($arg[1]['button'])){
				$body .= $this->getButton('1');
            } elseif (!isset($arg[1]['button']['default'])){
				$body .= $this->getButton('1');
            } elseif ($arg[1]['button']['default']==true){
				$body .= $this->getButton('1');
            } else {
				$body .= '';
            }
            if(!empty($arg[1]['button'])){
                foreach($arg[1]['button'] as $boton=>$buton){
                    if(is_array($buton)){
                        if (array_key_exists('type', $buton)&& low($buton['type']) == 'link'){
                            unset($buton['type']);
                            if (array_key_exists('url', $buton)){
                                    $link = $buton['url'];
                                    unset($buton['url']);
                            } else $link = './';
                            $body .= $html->link($boton, $link, $buton);
                        } else $body .= $form->submit($boton, $buton);
                    }
                }
            }
            $body.= '</p></div>'.$n;
            $body.= $form->end().$n;
            $body.='';
            return $body;
    }
    
    function getFunction($name){
            $this->userFunction = $name;
    }

    function restaFechas($dFecIni, $dFecFin){
        $dFecIni = str_replace('-','',$dFecIni);
        $dFecIni = str_replace('/','',$dFecIni);
        $dFecFin = str_replace('-','',$dFecFin);
        $dFecFin = str_replace('/','',$dFecFin);

        ereg( '([0-9]{1,2})([0-9]{1,2})([0-9]{2,4})', $dFecIni, $aFecIni);
        ereg( '([0-9]{1,2})([0-9]{1,2})([0-9]{2,4})', $dFecFin, $aFecFin);

        $date1 = mktime(0,0,0,$aFecIni[2], $aFecIni[1], $aFecIni[3]);
        $date2 = mktime(0,0,0,$aFecFin[2], $aFecFin[1], $aFecFin[3]);

        return round(($date2 - $date1) / (60 * 60 * 24));
    }

    function sumaFechas($givendate,$day=0,$mth=0,$yr=0) {
        $cd = strtotime($givendate);
        $newdate = date('Y-m-d h:i:s', mktime(date('h',$cd),
                date('i',$cd), date('s',$cd), date('m',$cd)+$mth,
                date('d',$cd)+$day, date('Y',$cd)+$yr));
        return $newdate;
    }

    function is_date($fecha){
        //Comprueba si la cadena introducida es de la forma D/m/Y (15/04/1920)
        if (ereg("([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})", $fecha, $bloques)){
            return checkdate($bloques[2], $bloques[3], $bloques[1]);
        } else if (ereg("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $fecha, $bloques)){
            return checkdate($bloques[2], $bloques[3], $bloques[1]);
        } else return false;
        return true;
    }
}
?>